home *** CD-ROM | disk | FTP | other *** search
/ Aminet 1 (Walnut Creek) / Aminet - June 1993 [Walnut Creek].iso / aminet / text / print / post_src_186enh.lha / postprog.doc < prev    next >
Text File  |  1993-01-27  |  34KB  |  683 lines

  1. PostScript interpreter - programmer documentation (Post V1.7)
  2. =============================================================
  3.  
  4. (C) Adrian Aylward 1989, 1992
  5.  
  6. Compiler assumptions
  7. ====================
  8.  
  9. We assume the following data sizes:
  10.  
  11.     char        1 byte
  12.     short       2 bytes
  13.     int         4 bytes
  14.     float       4 bytes
  15.     double      8 bytes
  16.     pointers    4 bytes
  17.  
  18. Any machine with enough memory to run the interpreter should be able to
  19. support 4 byte ints; otherwise wholesale modifications would be necessary
  20. to change ints to longs.  The size of the other types is less important; if
  21. they were different quite possibly it could be made to work, but it has not
  22. been tested.  The path fill and clipping routines assume the availability
  23. of double precision floating point that can handle integers of at least 48
  24. bits exactly.  The array packing and unpacking routines make assumptions
  25. about the data sizes of the interpreter objects.
  26.  
  27. The virtual machine memory allocation routine returns blocks aligned on 4
  28. byte boundaries; if this is insufficient change the value of "mcalign" in
  29. the main header file.
  30.  
  31. We use structure assignment, but not structure arguments.  We expect
  32. structure member names to be distinct for each different structure type.
  33. All modern compilers should support this.
  34.  
  35. We use ansi function prototypes.
  36.  
  37. We assume that long external symbol names are supported.
  38.  
  39. The choice of which variables to put in registers is left to the compiler.
  40.  
  41. The interpreter
  42. ===============
  43.  
  44. The interpreter is an infinite loop, only returning when the execution stack
  45. is emptied.  It is recursive: certain operators themselves call the
  46. interpreter. For example to show a character we must execute its description
  47. within the font, which is a postscript procedure.  Each recursion level has a
  48. separate long jump buffer in case of error.
  49.  
  50. The first part of the interpreter loop fetches an object to be interpreted.
  51. The object is stored into a local workspace, but is made available externally
  52. by the global pointer "currtoken".  It remains there for the rest of the
  53. interpreter cycle.
  54.  
  55. If the item at the top of the execution stack is executable it must be an
  56. array, a file or string, or an operator.  (The executable bit is never set
  57. for other types of object.)  The (dynamically) commonest case is an array,
  58. so we handle this first.  If we have reached the end of the array we pop it
  59. off the execution stack and loop.  Otherwise we extract the next element; if
  60. we have now reached the end we pop the array immediately so as to permit
  61. arbitrarily deep tail recursion.  The next commonest case is a file, or
  62. possibly a string. In either case we call the scanner to read the next token,
  63. popping the execution stack when we reach the end.  Executable operators will
  64. not usually be on the execution stack; if we find one we will pop it off and
  65. execute it.
  66.  
  67. The only common case of a non-executable object on top of the execution stack
  68. is a control operator, such as "for", "loop", "stopped" etc..  These
  69. operators have one or more arguments just below them on the stack
  70. representing loop variables or whatever.  In this case we call the operator
  71. routine, which can determine it is being called from the top of the execution
  72. stack by testing the control flag - accessible via "currtoken".  The routine
  73. will typically update the loop counter and push the procedure to be repeated
  74. onto the execution stack.  Or if we have finished the last iteration, it will
  75. just pop itself and its arguments.
  76.  
  77. In all other cases we simply pop the object off the top of the stack and
  78. interpret it.
  79.  
  80. The second part of the loop interprets the object we have fetched.  It
  81. appears in two versions; one executes objects obtained directly from the
  82. scanner or fetched from an array; the other is for objects obtained
  83. indirectly - via name lookup, or popped off the execution stack.  As the
  84. interpreter loop is speed critical we prefer to have two versions of the
  85. code rather than set and test a flag.  The only difference between them is
  86. that in the direct version executable arrays are pushed onto the operand
  87. stack, but if they were obtained indirectly they are pushed onto the
  88. execution stack to be executed immediately.
  89.  
  90. We order the cases so that the (dynamically) most frequent are tested for
  91. first. If the object is executable, then if it is an operator we call its
  92. routine, or if it is a name we look it up and jump back to interpret its
  93. value.  Other cases of executable objects are arrays (direct), files, or
  94. strings; these are pushed onto the execution stack for their contents to be
  95. interpreted. Executable nulls do nothing.  All non-executable objects (or
  96. indirect executable arrays) are pushed onto the operand stack.
  97.  
  98. The scanner
  99. ===========
  100.  
  101. The scanner returns the next object token from the input, which may be a file
  102. or a string.
  103.  
  104. Strings (ascii or hex) are copied directly into the next free locations in
  105. the virtual machine memory.  When we get to the end of the string we know its
  106. length, so we can allocate the block of memory that we have already copied
  107. the data into.
  108.  
  109. Executable arrays are constructed on the operand stack.  We recurse to scan
  110. each of the elements, then build the array object allocating virtual machine
  111. memory and moving the array data into it.  Packed arrays are packed directly
  112. into the virtual machine memory, in a similar fashion to strings.
  113.  
  114. The text for names and numbers is assembled into the name buffer.  When we
  115. have it all we first try to parse it as a number (unless a "/" preceded it);
  116. if this fails we build a name object.
  117.  
  118. When parsing a number we build an integer value being careful to check for
  119. overflow.  An integer without a radix that overflows is converted to a real.
  120. If a number with a radix overflows that is an error.  Real values are parsed
  121. only; we then call a library routine to convert the number to floating point.
  122.  
  123. Objects
  124. =======
  125.  
  126. All objects have an 8 byte representation.  Simple objects contain their
  127. entire value.  Composite objects contain pointers to their values.
  128.  
  129. Each object has a type field, a flags field, and a value field.  Objects
  130. such as arrays and strings have a length field.  Directories are special in
  131. that their flags are contained in the structure their value points to, rather
  132. than in the object itself.  (This is so that directory objects sharing the
  133. same value all have the same access permissions.)
  134.  
  135. Simple objects
  136. --------------
  137.  
  138. Null objects are are binary zeros, so arrays can be trivially initialised.
  139.  
  140. Integers, reals, and booleans are just a type, flags and a 'C' value field.
  141.  
  142. Save objects have a type, flags, level number and a generation number (see
  143. below).
  144.  
  145. Names
  146. -----
  147.  
  148. Names are structures kept in the name table.  The value of a name object is
  149. a pointer to the name structure.  There are no duplicates in the table, so
  150. name objects can be compared simply be comparing the pointers.
  151.  
  152. The name table is a hash table, each entry being a chain of name objects.
  153.  
  154. The string field of the name structure is a variable length array.  We set
  155. the array bound to 2 in the definition as the compiler may not like a bound
  156. of zero (and 2 makes the structure size a multiple of 4).  We adjust the size
  157. of the entire structure to allow for the actual bound when allocating the
  158. memory for it.
  159.  
  160. Dictionaries
  161. ------------
  162.  
  163. Dictionaries are hash tables.  The number of slots is 1.25 times the maximum
  164. number of entries + 1, rounded up to the next prime.  If we have a collision
  165. we can then rehash by adding the initial value of the hash index; since the
  166. table size is prime this process will look at all the slots in turn - unless
  167. we started with slot zero, when we add 1 instead.  The number of entries is
  168. limited to the number specified, so the table is never more than 80% full.
  169. There is always at least one empty slot, which we will find if they key we
  170. are looking for is not in the table.
  171.  
  172. The actual bit pattern of the key object less the flag bits is used as the
  173. table key.  This means that similar objects with different attribute or
  174. access permission flags will refer to the same entry.  The key hashing and
  175. comparison code assumes that the size of the key object structure is the same
  176. as two ints - and that there are no gaps within it with undefined bit
  177. patterns.
  178.  
  179. We store the access permissions in the dictionary structure so that all
  180. objects with it as their values have the same access permissions.
  181.  
  182. We store in the dictionary the save stack level of when it was last saved.
  183. Whenever we update it we check whether the save stack level number is
  184. greater; if so we must save it again before changing it.
  185.  
  186. The entries are a variable length array.  We set the array bound to 1 in the
  187. definition as the compiler may not like a bound of zero.  We adjust the size
  188. of the entire structure to allow for the actual bound when allocating the
  189. memory for it.
  190.  
  191. Arrays
  192. ------
  193.  
  194. Arrays are simply strings of objects.  They have no header structure, so
  195. subarrays can easily be referenced.  Unfortunately this means that saving and
  196. restoring them is rather less efficient (see below).
  197.  
  198. Packed arrays are readonly, so never need to be saved.  The length in the
  199. header is the number of objects, and cannot be used to determine the length
  200. in bytes.  The unpack routine unpacks the next element; for random access it
  201. must be called repeatedly to scan to the element required.
  202.  
  203. Strings
  204. -------
  205.  
  206. Strings are simply byte strings.  Like arrays the have no header.  They are
  207. not affected by save and restore.
  208.  
  209. Files
  210. -----
  211.  
  212. All file pointers are held in the file table.  The value of a file object is
  213. a subscript of this table.
  214.  
  215. Since more than one file object may refer to the same table slot each open
  216. file has a generation number.  Then if we reuse a slot it will be obvious if
  217. we use any old copies of file objects refering to the previous occupant.
  218.  
  219. Each slot also has an open mode flag so we can check whether the file is open
  220. for reading or writing without depending upon the operating system's error
  221. handling.
  222.  
  223. We also save the last character read from each file.  We can then determine
  224. when we read the first character of a line, and issue a prompt if the input
  225. is interactive.  We can also skip the rest of the line it we detect an error.
  226.  
  227. For encrypted files we also store the curent value of the pseudo random seed.
  228. The ecryption mode has values 0 = not encrypted, 1 = binary, 2 = hex, -1 =
  229. end of encrypted portion.
  230.  
  231. IBM font file format is supported directly.  The read character macro counts
  232. the size of the file segment, and calls a routine to skip the 6 byte segment
  233. headers.  As the eexec operator can read binary as well as hex, there is no
  234. need to translate the binary segments of the file.
  235.  
  236. The first 3 slots are reserved for %stdin, %stdout, %stderr.  These will have
  237. already been opened (as far as the operating system is concerned) before
  238. interpretation begins.  Attempts to close them are ignored.
  239.  
  240. Operators
  241. =========
  242.  
  243. Each operator has its own operator routine (except for aliases).  The value
  244. of the operator is an index into a function table; this is faster than
  245. using a switch statement in the interpreter loop, and is also more convenient
  246. for extensibility.
  247.  
  248. The routines are coded so that all error checking is completed before any of
  249. the stacks or contents of the virtual machine memory are altered.  This makes
  250. error recovery much simpler.
  251.  
  252. Virtual machine memory
  253. ======================
  254.  
  255. Memory is allocated sequentially, and is only recovered by a save/restore.
  256. So allocation is trivial.  Memory is initialised to a zero on startup and
  257. when recovered subsequently.  (N.B. when the scanner creates a string it
  258. writes to the memory BEFORE it has been allocated, so we can't initialise
  259. memory when we allocate it.)
  260.  
  261. To save the virtual machine state we save the values of the next free memory
  262. location and remaining length on the save stack.  We add a generation number
  263. so we can detect use of old copies of save objects.  We also initialise an
  264. empty list of saved dictionaries and arrays.
  265.  
  266. Whenever we update a dictionary we check to see if it is supposed to have
  267. been saved, but hasn't actually been yet.  This test can be done efficiently
  268. (see the description of the dictionary structure) as befits something likely
  269. to be done quite frequently.  If we do have to save it we allocate a block of
  270. memory and copy the entire directory into it, adding the block to the save
  271. list.
  272.  
  273. Arrays are not structured like directories.  So when we update one we test to
  274. see if the array is older than the most recent save.  If so we search the
  275. save list to see if it has already been saved.  This is much less efficient
  276. than the test for directories, but hopefully it won't happen quite so often.
  277. To speed up the search each save level has a small hash table of saved array
  278. lists.  (Unfortunately there is no header structure to an array, as it might
  279. be a subarray, so there is nowhere to store the save level to optimise the
  280. test.) If more than one different, possibly overlapping, subarray of an array
  281. is updated, then each may appear as a separate entry on the save lists.  It
  282. is important therefore that the most recently saved copies be linked first on
  283. the list, so that when the array is restored the data will be correct.
  284.  
  285. N.B. the last location of the hash table array is used for the dictionary
  286. save list and is not part of the table proper.
  287.  
  288. To restore the virtual machine we first check the stacks to make sure they do
  289. not contain any references to memory that is being recovered; otherwise they
  290. will be left dangling.  Then we close all files opened since the save, and
  291. delete all the more recent entries in the name table.  Then for each level we
  292. are restoring we restore the dictionaries and arrays in the save lists.
  293. Finally we reset the memory pointers and reinitialise the recovered memory.
  294.  
  295. Note that strings are not restored.  This is a (dubious) feature of the
  296. language specification.  At least it is safe, since strings cannot contain
  297. reference to other virtual machine objects.
  298.  
  299. The virtual machine is allocated in segments as they are needed.  If a block
  300. is too large for a single segment then multiple segments are allocated
  301. contiguously.  References from one object to another are not stored as
  302. machine addres pointers but rather as abstract references in the form of a
  303. segment number and offset.  This makes it very easy to compare to references
  304. to find out which is the most recent, when restoring the virtual machine.
  305.  
  306. Error handling
  307. ==============
  308.  
  309. Error trapping is controled by the variable "errorflag".  During
  310. initialisation this is set to 0 so any errors cause an immediate exit.
  311. During normal running it is set to 2 so that any errors are trapped; while
  312. the trap handler is being executed it is set to 1 to temporarily disable
  313. error trapping to prevent recursion if a further error occurs.
  314.  
  315. When an error is detected the routine "error" is called.  We save the error
  316. name, the current command and the stacks in memory.  We then extract the
  317. error routine from the error dictionary and call it - if there is room on
  318. the execution stack.  (If the trap handler is temporarily disabled we
  319. print an error message and return to the lowest level if we are running
  320. interactively, or otherwise we quit.)  We return to the interpreter loop by
  321. a longjump.
  322.  
  323. A special case of the error routine is a quit operation;  the error code has
  324. the value -1 and we just do the longjump without generating any error
  325. message.
  326.  
  327. The initial values of the error routines are simply the ".error" operator.
  328. This operator takes the error values stored in memory and copies them into
  329. the $error dictionary.  Then it tries to do a stop.  If there is no stopped
  330. operator on the execution stack we clear the execution stack down to the
  331. lowest interactive level as above and call the "handleerror" procedure.
  332.  
  333. The initial value of the "handleerror" procedure is the ".handleerror"
  334. operator.  This operator extracts the values stored in the $error dictionary
  335. and copies them into memory.  Then if the newerror flag was set we clear it
  336. and print an error message using the values we extracted.
  337.  
  338. Care should be taken when redefining the error routines.  If a further error
  339. occurs while interpreting them the error mechanism may loop.  If the
  340. execution stack overflows it will not be possible to call the error handler;
  341. the error message will instead be generated directly.  If the operand or
  342. dictionary stacks overflow then an error handler that tries to push anything
  343. onto them will fail.
  344.  
  345. Note that essentially any floating point operation may lead to an error
  346. trap if there is an overflow.  All routines using floating point are
  347. carefully written to ensure that their data structures are left consistent if
  348. this happens.
  349.  
  350. Recursion
  351. =========
  352.  
  353. Some operators have procedures as arguments: transfer functions, spot
  354. functions, image procedures, and character drawing and kerning procedures.
  355. These are executed by calling the interpreter recursively.
  356.  
  357. To prevent problems with dangling references etc. we make prevent vm and
  358. graphics stack restores from popping to a lower level than that current
  359. when recursion began.  When we exit from the recursion we always pop them.
  360.  
  361. To prevent mutual recursion within the routines that set up gray shades,
  362. and also within the imaging routines (that use static variables), we set
  363. a flag bit in the interpreter state.  Within this state vm and graphics
  364. stack saves and restores are not permitted.
  365.  
  366. We also set a flag bit when within a character drawing routine, so we know
  367. whether setcharwidth/setcachedevice are permitted.  Within a character
  368. procedure, if there has not been a vm save, the grestoreall operator has no
  369. effect.
  370.  
  371. The operators exit, execstack, countexecstack are limited to the execution
  372. stack belonging to their own level of recursion.  The stop operator (and
  373. error handling) will jump to outer levels of recursion if necessary; if
  374. this happens the vm and graphics stacks will be popped.
  375.  
  376. Graphics Operations
  377. ===================
  378.  
  379. Path construction
  380. -----------------
  381.  
  382. All path points are held in a single array.  The clipping path occupies the
  383. first entries, immediately followed by the current path.  If is is necessary
  384. to adjust the length of the clipping path (which doesn't happen very often)
  385. the current path is shuffled up or down to make room.  On a gsave operation
  386. the paths are copied so all the saved paths are present in the array in
  387. order.
  388.  
  389. If the path array becomes full a larger array is allocated in its place.
  390. So all the routines that add path elements have to be careful not to use
  391. pointers that might become invalid after the array has been extended.
  392.  
  393. If the clipping path is the default (i.e. the page boundaries) it is not
  394. stored in the path array, to avoid unnecessary copying on a gsave/restore.
  395.  
  396. Circles are constructed as a number of Bezier curves. It turns out that the
  397. number of Beziers needed is remarkably small, even for the largest arc that
  398. will fit onto the page.  We locate the control points to ensure that the
  399. slopes of the tangent at the endpoints is correct, as is also the height of
  400. the centre of the chord.
  401.  
  402. Beziers are converted to straight lines before the path is flattened.  We
  403. recursively split the curve into two until it is sufficiently flat to be
  404. approximated by a straight line.  If the path is explicitly flattened we
  405. flatten it in situ, otherwise we flatten it into the free space at the end
  406. of the path array, immediately before drawing it.
  407.  
  408. Fill operations always operate on closed paths.  It the path is not already
  409. closed (explicitly), we generate an implicit close.  The line corresponding
  410. to the close is used for filling and clipping, but is only stroked if the
  411. close is explicit.
  412.  
  413. Path Clipping
  414. -------------
  415.  
  416. The clipping algorithm proceeds in 3 steps:
  417.  
  418.     1)  Split all the lines at their intersections.  Great care must be
  419.         taken to ensure that floating point rounding errors do not cause
  420.         anomalies.  The code is carefully organised so the determination
  421.         of whether two lines intersect is exact.  (It does not matter too
  422.         much if the location of the endpoints slightly off due to rounding
  423.         errors; what is essential is that we do not miss an intersections
  424.         and generate topologically absurd figures.)  If two lines are
  425.         colinear they are considered to intersect at the endpoints.
  426.  
  427.     2)  Discard all the lines that are not on the boundary of the clip
  428.         region.  We calculate the winding numbers for both sides of the
  429.         line, and if one side is inside but not the other it must be on
  430.         the boundary.  There are various degenerate cases, where the new
  431.         region is of zero width.  Since PostScript always renders the
  432.         boundaries of its paths we generate a pair of coincident lines to
  433.         preserve the degenerate region.
  434.  
  435.     3)  Rejoin the lines to build the new clip path.  If all the preceding
  436.         operations were performed correctly they will join up into
  437.         closed subpaths.
  438.  
  439. By sorting the lines according to their y coordinates we can make the whole
  440. algorithm run in time proportional to N ** 1.5.
  441.  
  442. The workspace for path clipping reuses the same memory as for path filling.
  443.  
  444. Path Stroking
  445. -------------
  446.  
  447. First the path is flatten so it contains only straight lines.  Then each
  448. line segment of each subpath is stroked individually.  The lines are divided
  449. into segments as necessary according to the dash pattern.  Each segment is
  450. stroked individually; its stroke path is constructed and then filled using
  451. the standard path filling code.  Lines of zero length are ignored. If a
  452. subpath is not closed then we begin and end with a line cap, otherwise all
  453. teh lines are joined. Joints are constructed only at a beginning of the line;
  454. the joint at the end is constructed when the next line is stroked.
  455.  
  456. Path Filling
  457. ------------
  458.  
  459. We use what is basically a Y bucket list DDA scan line algorithm.  There are
  460. some additional complexities:
  461.  
  462.  
  463.     We only render line segments that are within both the clip and fill
  464.     paths.  We calculate the winding numbers for both paths using a
  465.     horizontal test line and render only when we are within both.
  466.  
  467.     We must render both pixels that are enclosed within the path and also
  468.     those that are on the boundaries.  This means that we have to calculate
  469.     the x coordinates for each line at both the bottom and the top of the
  470.     scan line pixels, and include the area between the values.
  471.  
  472. Keeping track of two sets of x coordinates for both clip and fill paths
  473. on the fly would be very awkward, so we generate a list of line segments
  474. for each, and effectively sort and merge the list.  (We use a simple scoring
  475. scheme that locates the interior of the segments).  We can then scan the
  476. list rendering segments as we go.
  477.  
  478. Care must be taken with the scaling of the line coordinates so that integer
  479. overflow will not happen, and that accuracy is not lost in the DDA (digital
  480. differential analyser).  When we initially set up the clip and fill lines we
  481. clip to the pages boundaries and scale to fixed point integers;  the rest of
  482. the algorithm then proceeds using much faster integer arithmetic.
  483.  
  484. The overheads of processing the clip path are only needed when a non-default
  485. clip path has been set up.  If we have only the initial clip path we can use
  486. a quicker version of the fill routine that omits processing of the clip
  487. lines, and runs about twice as fast.  Since we no longer have two sets of
  488. segment endpoints to merge, we can render them on the fly, dispensing with
  489. the segment list.
  490.  
  491. For type 1 fonts, when rendering to the font cache,  we use a special fill
  492. routine.  In this case we modify the algorithm slightly, to prevent excessive
  493. blackening in small point sizes.  So we only render the boudaries of the
  494. path when necessary to prevent dropout.  For right edges we simply skip the
  495. extra pixel unless the segment length is zero.  For top edges we only fill
  496. the pixels if the corresponding ones in the next lower row are blank.  Since
  497. we are rendering to the cache, there is necessarily only a single bit plane,
  498. and we always draw black.
  499.  
  500. The workspace for path filling is automatically extended as it is needed.
  501.  
  502. Imaging
  503. -------
  504.  
  505. There are two versions of the imaging routine, one fast and one slow.  If
  506. there is no clip path, and exactly one sample bit per pixel, and the image
  507. coordinates are the same as the device coordinates - except possibly for
  508. reversal of the y direction, then we can use the fast routine that copies
  509. the image data directly into the device buffer.
  510.  
  511. In the general case we must use the slow routine.  This routine can only
  512. handle rectangles, so if when we call the input procedures they return a
  513. number of bytes that does not correspond to an integral number of image lines
  514. we render it as 2 or 3 separate rectangles.
  515.  
  516. The slow rendering routine first constructs the path corresponding to the
  517. boundaries of the rectangle.  Then it uses the scan line algorithm, similar
  518. to that for path filling, to render its interior, suitably clipped.  At the
  519. start of a scan line segment it inverse transforms the device coordinates to
  520. image space to locate the corresponding sample.  For pixels it adds the
  521. inverse delta transform of a single pixel step.  We force the result to be
  522. within the image data, in case prevent rounding errors have shifted it
  523. slightly.  We unpack the sample values for the entire segment first.  Then
  524. to avoid repeatedly swapping halftone patterns we search for runs of a
  525. single shade and render them together.  If we have only a single input
  526. procedure we can precalculate the shades we will need; this is much faster
  527. than the multiple procedure case.
  528.  
  529. Halftones
  530. ---------
  531.  
  532. Setting up a new halftone screen is slow and complex.  The screen spot
  533. pattern itself is only recomputed when changed by the setscreen operator,
  534. or as a result of grestore.  For each possible gray level there is a
  535. different screen bit pattern, which must be changed every time we do a
  536. setgray or the like.  In the interests of efficiency we cache the bit
  537. patterns, preserving as many as we have memory for.
  538.  
  539. To set up a new spot pattern we first calculate the dimensions of the
  540. halftone cell when converted into device space.  This is complicated by
  541. the fact that the x and y pixel densities may be different, so the vertical
  542. component of the sides of the cell need not be the same as the horizontal
  543. component of the top and bottom.  We round the sizes to the nearest pixel,
  544. ensuring that the cell dimensions are at least 1, so that the area is never
  545. zero.  Then we calculate the area of the cell; this is the number of pixels
  546. within it, and one less than the number of gray levels. Then comes the
  547. interesting bit: we need to determine the number of pixels in the x and y
  548. direction (in device space) after which the pattern repeats itself.  Using
  549. a bit of number theory we can prove that this is equal to the area divided
  550. by the gcd of the x or y steps of the cell edges - not forgetting that
  551. the densities may be different for the two directions, and considering
  552. gcd(n,0) to be equal to n.  We repeat the spot pattern in the x direction
  553. as many times as necessary to make the x size a multiple of 8, so we are
  554. dealing in whole bytes.  So we now have the dimensions of the bit pattern.
  555. But within the bit pattern the spot pattern may also be repeated more than
  556. once in the y direction; each repetition being displaced horizontally.
  557. The distance at which it is repeated is equal to the area divided by the
  558. distance at which it is repeated in the x direction.  We need to calculate
  559. the distance by which it is displaced; then we can fill in the entire bit
  560. pattern without calculating the spot function more than once for each cell
  561. location.  Rather than resorting to number theory we locate this point by
  562. stepping along the cell edges until we get there, counting our displacement
  563. as we go.  With the preliminaries out of the way, (despite the length of
  564. the description, the calculation is quick) we proceed to call the spot
  565. function for each point in the cell.  We sort the results, remembering
  566. their order but discarding the actual values.
  567.  
  568. We are now ready to set up a bit pattern.  We never need to calculate
  569. patterns that are wholly black or white, as the drawing routines optimise
  570. them.  All the rest are cached, using cyclic replacement if we run out of
  571. cache slots.  If we can't  find the pattern we want, we create it by
  572. copying the next blacker one.  Then we clear all the bits whose spot value
  573. should be white but was black in the pattern we copied, replicating the
  574. spot bits in the x and y directions as necessary.
  575.  
  576.  
  577. Character Operations
  578. ====================
  579.  
  580. The font cache
  581. --------------
  582.  
  583. We cache the fonts we make.  This is so that repeated calls of makefont
  584. with identical parameters do not consume VM, and are also fast.  As a cache
  585. key we use the UniqueID value.  This is the easiest way to determine that
  586. two fonts are identical.  If it is not present then the font will not be
  587. cached. (Maybe we should use the disk key, instead?)  We also add the
  588. address of the encoding vector to the key, as it is legal to change the
  589. encoding without altering the UniqueID.  On a VM restore operation we must
  590. purge the cache entries whose font dictionaries are more recent than the
  591. corresponding save.
  592.  
  593. The character cache
  594. -------------------
  595.  
  596. It is crucial to the speed of character rendering that all the frequently
  597. used characters are copied from the cache rather than being redrawn each
  598. time they are needed (something like 100 times faster).  Each cache record
  599. is a different size, according to the dimensions of the character.  When
  600. we run out of free cache memory we use a variation on cyclic replacement;
  601. free slots are amalglamated.  Each slot has a count which is incremented each
  602. time it is used.  As we scan looking for a free slot we halve the counts,
  603. freeing the slot when the count reaches zero.  The algorithm is efficient,
  604. with performance intermediate between cyclic replacement and LRU.  Since
  605. character generation can be recursive, we have to be careful that while
  606. deep in the recursion we do not to free a slot being used at a lower level.
  607. So we temporarily set the usage count to a large number while building the
  608. character so it will not be freed.  The type 3 font mechanism is recursive,
  609. so we must be careful not to use so much cache space that there is none left
  610. for the lower levels of recursion without reusing the record we aallocated
  611. at the highest level.  So at the highest level we restrict our record to 1/3
  612. of the cache; that guarantees that there is a contiguous inactive space of
  613. at least another 1/3 no matter what fragmentation occurs.  At the next level
  614. we use no more than 1/9, then 1/27 etc..
  615.  
  616. As a cache key we use the character name (not the code, as we may change the
  617. encoding vector), the font UniqueID if we have one otherwise the dictionary,
  618. and the transformation matrix.  For fast searching we use a hash table.
  619. On a VM restore operation we must purge those cache entries keyed by names
  620. or dictionaries that are more recent than the corresponding save.  This
  621. doesn't usually happen for names as most of them are in StandardEncoding, and
  622. it won't happen for dictionaries if there is a UniqueID.  So characters can
  623. survive in the cache even after their fonts have been unloaded, at least
  624. until cache memory runs out.  (Maybe we could save the font cache to disk?)
  625.  
  626. If the character we want is in the cache we can image it directly into the
  627. page buffer.  The speed of this routine is critical to the performance of
  628. the interpreter.  If there is no clip path we can always do a fast cache
  629. copy.  Otherwise we set up the clip lines like we do for path filling.  If
  630. some of the lines intersect the rectangle to be imaged then the character
  631. must be clipped, so we do a slow cache copy.  Otherwise the character must
  632. either be wholly inside the clip path - when we can do a fast copy, or
  633. wholly outside - and we don't copy it at all.
  634.  
  635. The fast copy routine simply images the cache data directly into the page
  636. buffer.  The slow routine uses the line scan algorithm as for path filling.
  637. It generates line segments for the inside of the clip path, imaging the
  638. portions of each which are within the character rectangle.
  639.  
  640. The show routine
  641. ----------------
  642.  
  643. All the character drawing operations are handled by a single show routine.
  644. For charpath we never use the cache; whenever we do a fill or stroke
  645. instead of drawing in the page buffer the path is copied down to the saved
  646. graphics state.  For stringwidth we use the cache if the character is small
  647. enough; we skip both fill and stroke only if we are not using the cache, and
  648. we accumulate the width.  (The characters are then in the cache if we then
  649. want to show them).
  650.  
  651. Whenever we start a character procedure we round our current position to
  652. a pixel boundary, so all instances of a character have exactly the same
  653. bit pattern.
  654.  
  655. The setcachedevice operator diverts output from the page buffer to the
  656. cache - if the character is small enough.  It saves the width information
  657. in the cache record and initialises a bitmap for the character.  At the end
  658. of the build procedure the character is in the cache, and so can be imaged
  659. into the page buffer.
  660.  
  661. Type 1 fonts
  662. ------------
  663.  
  664. Type 1 fonts have their own interpreter to execute the character strings.
  665. Since the type 1 font mechanism cannot recurse we can use statically
  666. allocated variables.
  667.  
  668. The bounding box is calculated by scanning the character path after it has
  669. been generated, only then can we attempt to set the cache device.  So the
  670. path is built using a ctm based upon the character origin; if the character
  671. proves to be too big for the cache the path can be relocated later.
  672.  
  673. There is no facility for calling PostScript from within a character string.
  674. The Flex and hint redefinition routines are built in.
  675.  
  676. If the character fits within the cache a special version of the path
  677. filling routine is used.  It is rendered at eight bits per pixel in each
  678. direction, using a special line buffer.  The result is compressed to a
  679. single bit horizontally, one line at a time.  It is then shifted sideways
  680. into a second buffer; after eight lines have been processed this is then
  681. compressed onto the page.  The compression prevents dropout of fine line
  682. widths while avoiding excessive blackening of small character sizes.
  683.